#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

void read_from_pip(int fd) {
    char message[100];
    printf("等待读取...\n");
    read(fd, message, 100);
    printf("read from pip3: %s\n", message);
}

void write_to_pip(int fd) {
    sleep(400);
    char *message = "Hello, Pipe!\n";
    write(fd, message, strlen(message)+1);
}

int main(int argc, char const *argv[])
{
    int fd[2];
    pid_t pid;
    int stat_val;
    printf("pid: %d\n", getpid());
    if (pipe(fd)) {
        printf("create pipe failed!\n");
        exit(1);
    }
    pid = fork();
    switch (pid)
    {
    case -1:
        printf("fork error!\n");
        exit(1);
        break;
    case 0: // 子进程
        // close(fd[1]); //关闭fd写
        read_from_pip(fd[0]);
        exit(0);
        break;
    default: // 父进程
        // close(fd[0]); // 关闭读fd
        write_to_pip(fd[1]);
        wait(0);
        exit(0);
        break;
    }
    return 0;
}
